<template>
    <div class="table">
      <div class="container">
            <div class="handle-box">
                <el-button type="primary" size="mini" @click="deleteAllsinger()" >批量删除</el-button>
                <el-input
                  placeholder="请输入查询内容"
                  v-model="input"
                  maxlength="5"
                  style="width: 160px"
                  size="small"
                  clearable
                  >
                </el-input>
                <el-button type="primary" size="mini" @click="centerDialogVisible = true">添加歌手</el-button>
            </div>
        </div>
        <el-table :data="tableData.slice((currentPage-1)*pageSize,currentPage*pageSize)"
            size="mini"
            border
            style="width:100%"
            height="500px"
            @selection-change="selectChanges">
            <el-table-column
                type="selection"
                width="40px">
            </el-table-column>
            <el-table-column label="序号" width="40px">
            <template slot-scope="scope">
              {{scope.$index+1}} 
            </template>
            </el-table-column>
            <el-table-column prop="pic" label="歌手图片" width="110px" align="center">
                <template slot-scope="scope">
                    <div class="singer-img">
                        <img style="width:100%" :src="showUrl(scope.row.pic)"/>
                    </div>
                    <el-upload :action="uploadUrl(scope.row.id)" :on-success="Handsuccess">
                            <el-button size="mini">更新图片</el-button>
                    </el-upload>
                </template>
            </el-table-column>
            <el-table-column  prop="name" label="歌手" width="120px" align="center"></el-table-column>
            <el-table-column prop="sex" label="性别" width="40px" align="center">
                <template>
                   
                </template>
            </el-table-column>
            <el-table-column prop="birth" label="生日" width="90px" align="center">
                <template>
                  
                </template>
            </el-table-column>
            <el-table-column prop="location" label="地区" width="80px" align="center"></el-table-column>
            <el-table-column label="简介">
                <template slot-scope="scope">
                    <p style="height:100px;overflow:scroll">{{scope.row.introduction}}</p>
                </template>
            </el-table-column>
           
            <el-table-column
                    label="歌曲管理"
                    width="130px">
                <template slot-scope="scope">
            <el-row>
                  <el-button type="success" round @click="toSingList(scope.row.id)">歌曲管理</el-button>
            </el-row>
                 </template>
            </el-table-column>
         
            <el-table-column  
                    label="操作"
                    width="150px">
            <template slot-scope="scope">
            <el-button type="primary" icon="el-icon-edit" @click="update(scope.row.id)"></el-button>
            <el-button type="primary" icon="el-icon-delete" @click="deleteById(scope.row.id)"></el-button>
            </template>
            </el-table-column>
            
             
        </el-table>
        <div align="center">
             <el-pagination
            background
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="currentPage"
            :page-sizes="pageSizes"
            :page-size="pageSize" 
            layout="prev, pager, next"
            :total="totalCount"
            v-model="currentPage">
            <!--@current-change     currentPage 改变时会触发  -->
            <!--current-page        当前页数-->
            <!--page-sizes          每页显示个数选择器的选项设置-->
            <!--page-size           每页显示条目个数-->
            <!--layout              组件布局，子组件名用逗号分隔-->
            <!--total               总条目数-->
        </el-pagination>
        </div>
       
         <el-dialog title="添加歌手" :visible.sync="centerDialogVisible" width="400px" center>
            <el-form :model="registerForm" ref="registerForm" label-width="80px">
                <el-form-item prop="name" label="歌手名" size="mini">
                    <el-input v-model="registerForm.name" placeholder="歌手名"></el-input>
                </el-form-item>
                <el-form-item prop="sex" label="性别" size="mini">
                    <el-radio-group v-model="registerForm.sex">
                        <el-radio :label="0">女</el-radio>
                        <el-radio :label="1">男</el-radio>
                        <el-radio :label="2">组合</el-radio>
                        <el-radio :label="3">不明</el-radio>                        
                    </el-radio-group>
                </el-form-item>
                <el-form-item prop="birth" label="生日" size="mini">
                    <el-date-picker type="date" placeholder="选择日期" v-model="registerForm.birth" style="width:100%"></el-date-picker>
                </el-form-item>
                <el-form-item prop="location" label="地区" size="mini">
                    <el-input v-model="registerForm.location" placeholder="地区"></el-input>
                </el-form-item>
                <el-form-item prop="introduction" label="简介" size="mini">
                    <el-input v-model="registerForm.introduction" placeholder="简介" type="textarea"></el-input>
                </el-form-item>                
            </el-form>
            <span slot="footer">
                <el-button size="mini" @click="centerDialogVisible = false">取消</el-button>
                <el-button size="mini" @click="addSinger()">确定</el-button>
                
            </span>
        </el-dialog>

        <el-dialog title="修改歌手信息" :visible.sync="Visible" width="400px" center>
            <el-form :model="sterForm" ref="registerForm" label-width="80px">
                <el-form-item prop="name" label="歌手名" size="mini">
                    <el-input v-model="sterForm.name" placeholder="歌手名"></el-input>
                </el-form-item>
                <el-form-item prop="sex" label="性别" size="mini">
                    <el-radio-group v-model="sterForm.sex">
                        <el-radio :label="0">女</el-radio>
                        <el-radio :label="1">男</el-radio>
                        <el-radio :label="2">组合</el-radio>
                        <el-radio :label="3">不明</el-radio>                        
                    </el-radio-group>
                </el-form-item>
                <el-form-item prop="birth" label="生日" size="mini">
                    <el-date-picker type="date" placeholder="选择日期" v-model="sterForm.birth" style="width:100%"></el-date-picker>
                </el-form-item>
                <el-form-item prop="location" label="地区" size="mini">
                    <el-input v-model="sterForm.location" placeholder="地区"></el-input>
                </el-form-item>
                <el-form-item prop="introduction" label="简介" size="mini">
                    <el-input v-model="sterForm.introduction" placeholder="简介" type="textarea"></el-input>
                </el-form-item>                
            </el-form>
            <span slot="footer">
                <el-button size="mini" @click="Visible = false">取消</el-button>
                <el-button size="mini" @click="updateTwo()">确定</el-button>
                
            </span>
        </el-dialog>
    </div>
</template>

<script>
import { mixin } from '../mixins/index';
import {setSinger} from '../api/index';
import {selectSinger} from "../api/index";
import {deleteSinger} from "../api/index";
import {selectById} from "../api/index";
import {updateSinger} from "../api/index";
import {selectByName} from "../api/index";
import {selectBySex} from "../api/index";
import {deleteAll} from "../api/index";
export default {
    mixins: [mixin],
    data(){
        return{
            // 定义表单要绑定的数据
            registerForm: {
                name:'',
                sex:'',
                birth:'',
                location:'',
                introduction:''
            },
            sterForm: {
                name:'',
                sex:'',
                birth:'',
                location:'',
                introduction:''
            },
            tableData: [],
            centerDialogVisible: false,
            Visible: false,
            //绑定搜索框
            input: '',
            // <!--@current-change     currentPage 改变时会触发  -->
            // <!--current-page        当前页数-->
            // <!--page-sizes          每页显示个数选择器的选项设置-->
            // <!--page-size           每页显示条目个数-->
            // <!--layout              组件布局，子组件名用逗号分隔-->
            // <!--total               总条目数-->
            // 默认显示第几页
            currentPage:1,
            // 总条数，根据接口获取数据长度
            totalCount:3,
            // 个数选择器
            pageSizes:[1,2,3,4],
            // 默认每页显示的条数
            pageSize:3,

            selected:[],
        }
    },
    watch: {
    // 检测查询变化
    input: {
      handler() {
        //参数变化时需要执行的代码
        this.selectByName(this.input)
          },
        deep: true
        },

    totalCount(){
        if(this.totalCount==(this.currentPage-1)*this.pageSize){
            this.currentPage-=1;
            this.getData()
        }
    }

      
     },
    created(){
       //调用getData方法，实现初始化歌手信息的数据
       this.getData();
    },
    
    methods:{
        //查询所有歌手信息
        getData(){
            //需要调用 api/index.js中的方法向后台发送ajax请求
             selectSinger()
                .then((res) =>{
                this.tableData=res.singerlist
                for(let i = 0; i < this.tableData.length;i++){
                    this.tableData[i].birth = this.tableData[i].birth.substr(0,10)
                    if(this.tableData[i].sex==0){
                    this.tableData[i].sex='女'
                }else if(this.tableData[i].sex==1){
                    this.tableData[i].sex='男'
                }else if(this.tableData[i].sex==2){
                    this.tableData[i].sex='组合'
                }else if(this.tableData[i].sex==3){
                    this.tableData[i].sex='不明'
                }
                } 
                this.totalCount = this.tableData.length;
                });
        },
            // <!--@current-change     currentPage 改变时会触发  -->
            // <!--current-page        当前页数-->
            // <!--page-sizes          每页显示个数选择器的选项设置-->
            // <!--page-size           每页显示条目个数-->
            // <!--layout              组件布局，子组件名用逗号分隔-->
            // <!--total               总条目数-->
        handleSizeChange(val) {
            // 改变每页显示的条数
            this.Pagesize=val
            // 注意：在改变每页显示的条数时，要将页码显示到第一页
            this.currentPage=1
        },
        handleCurrentChange(val) {
            // 改变默认的页数
            this.currentPage=val
        },

        selectChanges(val){
            this.selected = val

            console.log(this.selected)
        },
        deleteAllsinger(){
            let params = new URLSearchParams();
            let ids = [];
            for(let i = 0 ; i <this.selected.length;i++){
                ids.push(this.selected[i].id)
            }
            if(ids.length == 0){
                 this.notify("请选择要删除的歌手","error");
                 return;
            }
            params.append('id',ids);
            deleteAll(params)
            .then(res => {
                if(res.code == 1){
                    this.notify("删除成功","success");
                    this.getData();
                }else{
                    this.notify("删除失败","error");
                }
            })
            .catch(err => {
                console.log(err);
            });
        },
        //上传成功是的钩子
        Handsuccess(){
            this.getData();
        },
        //添加歌手
        addSinger(){
            let d = this.registerForm.birth;
            let datetime = d.getFullYear()+'-'+(d.getMonth()+1)+'-'+d.getDate();
            let params = new URLSearchParams();
            params.append('name',this.registerForm.name);
            params.append('sex',this.registerForm.sex);
            params.append('pic','/img/singerPic/hhh.jpg');
            params.append('birth',datetime);
            params.append('location',this.registerForm.location);
            params.append('introduction',this.registerForm.introduction);
            setSinger(params)
            .then(res => {
                if(res.code == 1){
                    this.notify("添加成功","success");
                    this.getData();
                }else{
                    this.notify("添加失败","error");
                }
            })
            .catch(err => {
                console.log(err);
            });
            this.centerDialogVisible = false;
            this.registerForm = {};

        },
        //更新图片
        uploadUrl(index) {
            //需要调用 api/index.js中的方法向后台发送ajax请求
            return `http://localhost:8888/singer/postUpdate?id=${index}`

        },
        showUrl(url){
            return `http://localhost:8888/${url}`
        },
        
        update(index){
        //修改信息 
        //先根据id查询
        this.Visible = true;
        let params = new URLSearchParams();
        params.append('id',index);
        selectById(params)
         .then(res => {
               this.sterForm=res.singer
            })
            .catch(err => {
                console.log(err);
            });
        },
        //之后调用修改方法
        updateTwo(){
        let params = new URLSearchParams();
        params.append('id',this.sterForm.id);
        params.append('name',this.sterForm.name);
        params.append('sex',this.sterForm.sex);
        params.append('birth',this.sterForm.birth);
        params.append('location',this.sterForm.location);
        params.append('introduction',this.sterForm.introduction);
        updateSinger(params)
         .then(res => {
                if(res.code == 1){
                    this.notify("修改成功","success");
                    this.Visible = false;
                    this.getData();
                }else{
                    this.notify("修改失败","error");
                }
            })
            .catch(err => {
                console.log(err);
            });
        },

        deleteById(index){
        //根据id删除歌手
    
        let params = new URLSearchParams();
        params.append('id',index);
        deleteSinger(params)
        .then(res => {
                if(res.code == 1){
                    this.notify("删除成功","success");
                    this.getData();
                }else{
                    this.notify("删除失败","error");
                }
            })
            .catch(err => {
                console.log(err);
            });
        },

        selectById(index){
        //根据id(主键)查询某个歌手
        },
        
        // choose(stk){
        //     if(stk.typeof==String){
        //         this.selectByName(stk);
        //     }
        //     if(stk.typeof==Number){
        //         this,selectBySex(stk);
        //     }
        // },

        selectByName(stk){
        //根据歌手名字模糊查询
        let params = new URLSearchParams();
        params.append('name',stk);
        selectByName(params)
         .then(res => {
              this.tableData=res.singerlist
            })
            .catch(err => {
                console.log(err);
            });

        },

        selectBySex(stk){
        //根据歌手性别模糊查询
        let params = new URLSearchParams();
        params.append('sex',stk);
        selectBySex(params)
         .then(res => {
              this.tableData=res.singerlist
            })
            .catch(err => {
                console.log(err);
            });
        },
        toSingList(id){
            localStorage.setItem('singerId',id);
            this.$router.push(
              "/SingList"
            );
        }
    }
}
</script>

<style scoped>
    .handle-box{
        margin-bottom: 20px;
    }
    .singer-img{
        width: 100%;
        height: 80px;
        border-radius: 5px;
        margin-bottom: 5px;
        overflow: hidden;
    }
</style>